package cn.com.klun.tjy.test.ZookeeperTest;

import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.apache.zookeeper.ZooDefs.Ids.OPEN_ACL_UNSAFE;

public class ZkClient implements Watcher{
    private static final Logger logger = LoggerFactory.getLogger(ZkClient.class);

    ZooKeeper zk;
    String hostPort;
    //
    ZkClient(String hostPort) {
        this.hostPort = hostPort;
    }
    void startZK() throws Exception {
        zk = new ZooKeeper(hostPort,15000,this);
    }
    String queueCommand(String command) throws Exception {
        while(true){
            try {
                String name = zk.create("/tasks/task-",
                                        command.getBytes(),
                                        OPEN_ACL_UNSAFE,
                        CreateMode.EPHEMERAL_SEQUENTIAL);
                    return name;
            } catch (KeeperException.NodeExistsException e) {
                throw new Exception("异常已经存在这个节点");
            } catch (KeeperException e) {
            } catch (InterruptedException e) {
            }
        }
    }
    @Override
    public void process(WatchedEvent watchedEvent) {
        logger.info("watchedEvent"+watchedEvent);
    }

    public static void main(String[] args) throws Exception {
        ZkClient c = new ZkClient("192.168.137.11:2181");
        c.startZK();
        String name = c.queueCommand("zkclientTest");
        logger.debug("节点名称"+name);
    }
}
